//
//  IDTools.m
//  FMDB_Demo_Login
//
//  Created by libertyair on 15/5/28.
//  Copyright (c) 2015年 libertyair. All rights reserved.
//

#import "IDTools.h"
#import "FMDB.h"

@implementation IDTools

static FMDatabase *db = nil;
+ (void)initialize
{
    // 0.获得沙盒中的数据库文件名
    NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.sql"];
    
    // 1.创建数据库实例对象
    db = [FMDatabase databaseWithPath:filename];
    NSLog(@"%@",filename);
    // 2.打开数据库
    if ( [db open] )
    {
        LALog(@"数据库打开成功");
        
        // 创表
        BOOL result = [db executeUpdate:@"create table if not exists t_ID (userName text primary key, password text);"];
        
        if (result)
            LALog(@"创表成功");
        else
            LALog(@"创表失败");
    }
    else
        LALog(@"数据库打开失败");
    
}

/*
 添加一个账号
 */
+ (BOOL)addID:(User *)user
{
    return [db executeUpdate:@"insert into t_ID (userName, password) values (?, ?);", user.userName, user.password];

}

/*
 验证id是否正确
 */
+ (BOOL)verification:(User *)user
{
    // 1.查询数据
    FMResultSet *rs = [db executeQuery:@"select * from t_ID where userName = ? and password = ?;", user.userName,user.password];
    
    // 2.遍历结果集
    while (rs.next) {
//        NSString *userName = [rs stringForColumn:@"userName"];
//        NSString *password = [rs stringForColumn:@"password"];
//        
//        LALog(@"%@ %@", userName, password);
        return YES;
    }
    return NO;
}


@end
